package io.github.yotta.notice.sms.autoconfiguration;

import io.github.yotta.notice.sms.properties.AliSmsAccount;
import io.github.yotta.notice.sms.properties.AliSmsProperties;
import io.github.yotta.notice.sms.aliyun.channel.AliSmsNoticeChannel;
import io.github.yotta.notice.sms.aliyun.token.AliSmsTokenProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author yotta
 * @date 2023/4/29 16:52
 */
@Configuration
@EnableConfigurationProperties(AliSmsProperties.class)
@ConditionalOnClass(AliSmsNoticeChannel.class)
public class AliSmsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(AliSmsTokenProvider.class)
    public AliSmsTokenProvider aliSmsTokenProvider(AliSmsProperties properties) {

        AliSmsTokenProvider aliSmsTokenProvider = new AliSmsTokenProvider();
        // 设置默认的账户信息
        AliSmsAccount defaultAccount = properties.getDefaultAccount();
        if (defaultAccount != null) {
            aliSmsTokenProvider.setDefaultToken(defaultAccount.toToken());
        }
        final List<AliSmsAccount> otherAccounts = properties.getOtherAccounts();
        if (CollectionUtils.isNotEmpty(otherAccounts)) {
            otherAccounts.forEach(e -> aliSmsTokenProvider.registerToken(e.getTenantId(), e.toToken()));
        }
        return aliSmsTokenProvider;
    }

    @Bean
    @ConditionalOnMissingBean(AliSmsNoticeChannel.class)
    public AliSmsNoticeChannel aliSmsNoticeChannel(AliSmsTokenProvider aliSmsTokenProvider) {
        return new AliSmsNoticeChannel(aliSmsTokenProvider);
    }
}
